<template>
  <div>
    <el-dialog
      :title="type == 'add' ? '新增' : '编辑'"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeEditDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="addInfo"
        :rules="rules"
        ref="refAddInfo"
        label-width="60px"
      >
        <el-form-item size="small" label="名称" prop="name">
          <el-input
            clearable
            v-model.trim="addInfo.name"
            placeholder="请输入名称"
            maxlength="20"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
        <el-button
          size="small"
          @click="editSubmit"
          v-preventReClick="1000" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqCategoryAdd, reqCategoryEdit } from "@/api/model";

export default {
  name: "",
  props: ["type", "editInfo"],
  data() {
    return {
      dialogVisible: false,
      addInfo: {
        name: "",
      },

      // 表单验证规则
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
    };
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        switch (this.type) {
          case "add":
            this.addInfo.name = "";
            break;
          case "edit":
            this.addInfo.name = this.editInfo.name;
        }
      }
    },
  },
  methods: {
    // 点击
    async editSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.type == "add") {
            res = await reqCategoryAdd({
              data: {
                name: this.addInfo.name,
              },
            });
          } else if (this.type == "edit") {
            res = await reqCategoryEdit({
              data: {
                id: this.editInfo.id,
                name: this.addInfo.name,
              },
            });
          }
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("操作成功");
          this.$parent.onCategoryList();
          this.closeEditDialog();
        }
      });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.$refs.refAddInfo.resetFields();
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");
</style>
